package com.cskaoyan.wordmemorize.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cskaoyan.wordmemorize.dao.entity.LevelPrivilegeDO;
import com.cskaoyan.wordmemorize.dao.entity.UserDO;
import com.cskaoyan.wordmemorize.dao.mapper.LevelPrivilegeMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserMapper;
import com.cskaoyan.wordmemorize.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    EmployeeService employeeService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    LevelPrivilegeMapper levelPrivilegeMapper;

    /*
         只需要自己实现这个方法即可
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Long currentId = Long.parseLong(loginId.toString());
        List<String> permissionList = null;
        if ("admin".equals(loginType)){
            Set<String> permissionAlias = employeeService.getPermissionAlias(currentId);
            permissionList = permissionAlias.stream().filter(a-> a!=null && !a.isEmpty()).toList();
        } else if ("user".equals(loginType)) {
            // 获得当前用户的level value
            UserDO userDO = userMapper.selectById(currentId);
            Integer levelValue = userDO.getLevelValue();

            // 直接在level_privilege表中获得level_value小于等于当前用户的level value的所有privilege_code
            // 默认level_value唯一，且与等级绑定
            LambdaQueryWrapper<LevelPrivilegeDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.le(LevelPrivilegeDO::getLevelValue, levelValue);
            List<LevelPrivilegeDO> levelPrivilegeDOS = levelPrivilegeMapper.selectList(queryWrapper);
            permissionList = levelPrivilegeDOS.stream().map(LevelPrivilegeDO::getPrivilegeCode).collect(Collectors.toList());
        }
        permissionList.forEach(System.out::println);
        return permissionList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return null;
    }
}
